package com.dx.aop;


import com.dx.annoation.RequiredPermission;
import com.dx.exception.PermissionVerifyException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class PermissionCheckAop {
    //模拟用户拥有的权限
    public static final String [] PERMISSIONS = {"user:add","user:update"};


    @Pointcut("execution(* com.dx.controller.*.*(..))&&@annotation(com.dx.annoation.RequiredPermission)")
    public void point() {}


    @Before("point()")
    public void checkPermission(JoinPoint joinPoint)
    {
       log.info("权限检查");
       MethodSignature signature=(MethodSignature)joinPoint.getSignature();
       RequiredPermission annotation = signature.getMethod().getAnnotation(RequiredPermission.class);
       String[] permissions = annotation.permissions();
       for (String permission : permissions) {
           log.info("权限：{}",permission);
           if(!havePermission(permission)){
               throw new PermissionVerifyException("权限不足");
           }
       }

    }

    private boolean havePermission(String permission) {
        for (String p : PERMISSIONS) {
            if(p.equals(permission)){
                return true;
            }
        }
        return false;
    }
}
